package com.atguigu.jucdemo.safe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NotSafeDemo {
    private  static void listNotSafe()
    {
        // List<String> list=new ArrayList<>();
        //解决高并发：方法一：使用线程安全的Vector
        //List<String> list=new Vector<>();
        //解决高并发：方法二：使用线程安全的CopyOnWriteArrayList（推荐）
        List<String> list = new CopyOnWriteArrayList<>();
        //解决高并发：方法三：集合工具类的方法
        //List<String> list = Collections.synchronizedList(new ArrayList<>());

        for (int i = 0; i < 15; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    list.add(UUID.randomUUID().toString().substring(0,6));
                    System.out.println(list);
                }
            },String.valueOf(i)).start();
        }
    }

    private static void setNotSafe()
    {
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    private static void mapNotSafe()
    {
        Map<String,String> map = new ConcurrentHashMap();
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,6));
                    System.out.println(map);
                }
            },String.valueOf(i)).start();
        }
    }




    public static void main(String[] args) {
        //NotSafeDemo.listNotSafe();
        //NotSafeDemo.setNotSafe();
        //NotSafeDemo.mapNotSafe();
        NotSafeDemo.notsafe();
    }

    //线程不安全的案例
    public static void notsafe(){
        List<String> list=new ArrayList();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(list);
            },Thread.currentThread().getName()).start();
        }
    }


}
